package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

func NewApp(data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableAppVersion, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func UpdateApp(data map[string]interface{}, id int64) (int64, error) {
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableAppVersion, data, condition)
	o := NewDBOrm(DBChessSysData)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func DeleteApp(id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf("id = %v", id)
	sql := DeleteSql(TableAppVersion, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func AppInfoById(id int64, multiOrm ...orm.Ormer) (*APP, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableAppVersion, id)
	var app APP
	o := NewOrm(multiOrm, DBChessSysData)
	err := o.Raw(sql).QueryRow(&app)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &app, err
}

func ListApp(p ListParams, multiOrm ...orm.Ormer) ([]*APP, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		LIMIT ?,?
		`, TableAppVersion)
	o := NewOrm(multiOrm, DBChessSysData)
	var gl []*APP
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&gl)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v`,
		TableAppVersion)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return gl, count, nil
}
